package com.xu.base.advice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xu.base.model.BaseResponse;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 控制器统一返回结构
 *
 * @Author: 许乾伟
 * @Date: 2023/12/5  16:48
 */
@RestControllerAdvice(basePackages = "com.xu")
public class ControllerResponseAdvice implements ResponseBodyAdvice<Object> {
    /**
     * 异常返回
     * @param ex
     * @return
     */
    @ExceptionHandler
    public BaseResponse errorHandler(Exception ex){
        return BaseResponse.failed(ex.getMessage());
    }


    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converterType) {
        //如果返回本身就是Response类型或有NotControllerResponseAdvice注解的都不用在进行包装，直接返回
        return !(methodParameter.getParameterType().isAssignableFrom(BaseResponse.class)
                || methodParameter.hasMethodAnnotation(NotControllerResponseAdvice.class));
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // String类型不能直接包装
        if (returnType.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 将数据包装在BaseResponse里后转换为json串进行返回
                return objectMapper.writeValueAsString(BaseResponse.success(body));
            } catch (JsonProcessingException e) {
                throw new Exception("ControllerResponseAdvice String 封装失败");
            }
        }
        // 否则直接包装成BaseResponse返回
        return BaseResponse.success(body);
    }
}
